package com.qdairlines.common;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.ldap.LdapContext;

/**
 * ad用户名密码认证
 * @author zhangxu
 * @date 2016年12月13日
 * @company QingDao Airlines
 * @description
 */
public class ADUtil {
	
	LdapContext ldapCtx = null;
	
	public  static boolean checkUserPassword(String userName, String password) {
		// TODO Auto-generated method stub
		userName = userName + "@qdairlines.com";
		String host = "192.168.2.250"; // AD服务器IP（一共2个AD域服务器，备份的效果，另一个是10.156.129.95）
		String port = "389"; // 端口

		String url = new String("ldap://" + host + ":" + port);

		Hashtable<Object, String> env = new Hashtable<Object, String>();
		DirContext ctx;
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory");
		// env.put(Context.SECURITY_AUTHENTICATION, "none");
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.PROVIDER_URL, url);
		// env.put(Context.SECURITY_PRINCIPAL, DN_CN+","+DN_OU);
		env.put(Context.SECURITY_PRINCIPAL, userName);
		env.put(Context.SECURITY_CREDENTIALS, password);

		try {
			ctx = new InitialDirContext(env);// 初始化上下文
			System.out.println("认证成功");

			ctx.close();
			return true; // 验证成功返回name
		} catch (javax.naming.AuthenticationException e) {
			System.out.println("认证失败");
			System.out.println("e.getExplanation():" + e.getExplanation());
			System.out.println("e.getMessage():" + e.getMessage());
			return false;
		} catch (Exception e) {
			System.out.println("认证出错：" + e);
			return false;
		}
	}
}
